<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="设备编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deviceCode']" placeholder="请输入设备编码"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deviceName']" placeholder="请输入设备名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="型号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deviceType']" placeholder="请输入型号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="购置单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input v-decorator="['buyDepart']"
              placeholder="请输入购置单位"></a-input>-->
              <j-select-depart v-decorator="['buyDepart']" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="购置时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择购置时间" v-decorator="['buyDate']" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="检验时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择检验时间" v-decorator="['warnDate']" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="报废时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择报废时间" v-decorator="['scrapDate']" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="使用单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input v-decorator="['useDepart']"
              placeholder="请输入使用单位"></a-input>-->
              <j-select-depart v-decorator="['useDepart']" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="是否租赁" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['isRent']" :trigger-change="true" dictCode="is_rent" placeholder="请选择是否租赁" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="工器具类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-decorator="['deviceSort']"
                :trigger-change="true"
                dictCode="device_sort"
                placeholder="请选择工器具类型"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="是否出库" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['isOut']" :trigger-change="true" dictCode="is_out" placeholder="请选择是否出库" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="最大出力" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['maxOutput']" placeholder="请输入最大出力"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="保管人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deviceKeeper']" placeholder="请输入保管人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deviceNote']" placeholder="请输入备注"></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="使用说明书" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-upload
                :multiple="false"
                :action="uploadFile"
                :defaultFileList="testFile"
                :fileList="files"
                :headers="headers"
                @change="handleChange"
              >
                <a-button>
                  <a-icon type="upload" />选择文件
                </a-button>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="合格证书" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-upload
                :multiple="false"
                :action="uploadFile1"
                :fileList="files1"
                :defaultFileList="defaultFileList1"
                :headers="headers"
                @change="handleChange1"
              >
                <a-button>
                  <a-icon type="upload" />选择文件
                </a-button>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="操作规范" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-upload
                :multiple="false"
                :action="uploadFile2"
                :defaultFileList="defaultFileList2"
                :fileList="files2"
                :headers="headers"
                @change="handleChange2"
              >
                <a-button>
                  <a-icon type="upload" />选择文件
                </a-button>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'

export default {
  name: 'DeviceInfoForm',
  components: {
    JFormContainer,
    JSelectDepart,
    JDate,
    JDictSelectTag,
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      testFile: [],
      defaultFileList1: [],
      defaultFileList2: [],
      uploadVisible: true,
      files2: [],
      files1: [],
      files: [],
      uploadFileList: [],
      headers: {
        authorization: 'authorization-text',
      },
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: '/device/deviceInfo/add',
        edit: '/device/deviceInfo/edit',
        queryById: '/device/deviceInfo/queryById',
        uploadFile: '/device/deviceInfo/uploadFile',
        downloadFile: '/device/deviceInfo/files',
      },
    }
  },
  computed: {
    uploadFile: function () {
      return `${window._CONFIG['domianURL']}/${this.url.uploadFile}` + '?type=1'
    },
    uploadFile1: function () {
      return `${window._CONFIG['domianURL']}/${this.url.uploadFile}` + '?type=2'
    },
    uploadFile2: function () {
      return `${window._CONFIG['domianURL']}/${this.url.uploadFile}` + '?type=3'
    },
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  methods: {
    handleChange(info) {
      console.log('fileinfo', info)
      this.files = info.fileList
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (!info.file.response.success) {
          this.$message.error(`${info.file.response.message} file upload failed.`)
          this.files = this.files.filter((t) => t.uid != info.file.uid)
          return
        }
        this.$message.success(`${info.file.name} file uploaded successfully`)
        this.uploadFileList = this.uploadFileList.concat(info.file.response.result)
        console.log('upload', this.uploadFileList)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
      if (info.file.status === 'removed') {
        this.uploadFileList = this.uploadFileList.filter((m) => m != info.file.response.result)
        console.log('removed', this.uploadFileList)
      }
    },
    handleChange1(info) {
      console.log('fileinfo', info)
      this.files1 = info.fileList
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (!info.file.response.success) {
          this.$message.error(`${info.file.response.message} file upload failed.`)
          this.files1 = this.files1.filter((t) => t.uid != info.file.uid)
          return
        }
        this.$message.success(`${info.file.name} file uploaded successfully`)
        this.uploadFileList = this.uploadFileList.concat(info.file.response.result)
        console.log('upload', this.uploadFileList)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
      if (info.file.status === 'removed') {
        this.uploadFileList = this.uploadFileList.filter((m) => m != info.file.response.result)
        console.log('removed', this.uploadFileList)
      }
    },
    handleChange2(info) {
      console.log('fileinfo', info)
      this.files2 = info.fileList
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (!info.file.response.success) {
          this.$message.error(`${info.file.response.message} file upload failed.`)
          this.files2 = this.files2.filter((t) => t.uid != info.file.uid)
          return
        }
        this.$message.success(`${info.file.name} file uploaded successfully`)
        this.uploadFileList = this.uploadFileList.concat(info.file.response.result)
        console.log('upload', this.uploadFileList)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
      if (info.file.status === 'removed') {
        this.uploadFileList = this.uploadFileList.filter((m) => m != info.file.response.result)
        console.log('removed', this.uploadFileList)
      }
    },
    getFormFieldValue(field) {
      return this.form.getFieldValue(field)
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.uploadFileList = []
      this.files = []
      this.files1 = []
      this.files2 = []
      if (JSON.stringify(record) == '{}') {
        this.files = []
        this.files1 = []
        this.files2 = []
      } else {
        let params = { id: record.id }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            var files = res.result.deviceFiles
            for (let item of files) {
              this.uploadFileList.push(item.id)
              let url = `${window._CONFIG['domianURL']}/${this.url.downloadFile}/${item.fileLocation}`
              let file = { uid: item.id, name: item.fileName, status: 'done', url: url, response: { result: item.id } }
              if (item.fileType === 1) {
                this.files.push(file)
              } else if (item.fileType === 2) {
                this.files1.push(file)
              } else if (item.fileType === 3) {
                this.files2.push(file)
              }
            }
          }
        })
      }
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      console.log('model', this.model)
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'deviceCode',
            'deviceName',
            'deviceType',
            'buyDepart',
            'buyDate',
            'useDepart',
            'isOut',
            'isRent',
            'deviceSort',
            'maxOutput',
            'deviceKeeper',
            'deviceNote'
          )
        )
      })
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          this.model.fileLists = this.uploadFileList

          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          console.log('model', this.model)
          console.log('values', values)
          let formData = Object.assign(this.model, values)
          console.log('表单提交数据', formData)
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'deviceCode',
          'deviceName',
          'deviceType',
          'buyDepart',
          'buyDate',
          'useDepart',
          'isRent',
          'deviceSort',
          'maxOutput',
          'deviceKeeper',
          'deviceNote'
        )
      )
    },
  },
}
</script>